<template>
    <div class="page-root">
        <h2 class="main-title">菜品管理</h2>

        <!-- 查询表单 -->
        <el-form :inline="true" :model="searchForm" class="search-bar"
            style="display: flex; justify-content: space-between">
            <div style="display: flex; gap: 1em;">
                <el-form-item label="膳食名：">
                    <el-input v-model="searchForm.name" placeholder="请输入菜品名" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchData">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </div>
            <div>
                <el-button type="success" @click="openAddDialog">新建</el-button>
            </div>
        </el-form>

        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%; margin-top: 20px; background: #f5f7fa"
            :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }">

            <el-table-column prop="name" label="膳食名称" min-width="20%" />
            <!-- 图片列和修改按钮 -->
            <el-table-column label="图片" min-width="14%">
                <template #default="scope">
                    <div style="display: flex; flex-direction: column; align-items: center; gap: 4px;">
                        <el-image
                            v-if="scope.row.imgUrl"
                            :src="scope.row.imgUrl"
                            style="width: 48px; height: 48px; border-radius: 8px"
                            :preview-src-list="[scope.row.imgUrl]"
                            preview-teleported
                            fit="cover"
                        />
                        <span v-else style="color: #aaa;">暂无</span>
                        <!-- 修改图片按钮 -->
                        <el-upload
                            action=""
                            :show-file-list="false"
                            :before-upload="file => handleChangeImage(scope.row, file)">
                            <el-button size="small" type="primary" plain>修改图片</el-button>
                        </el-upload>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="30%" />
            <el-table-column label="状态" min-width="10%">
                <template #default="scope">
                    <el-tag :type="scope.row.status === '1' ? 'success' : 'info'" effect="plain">
                        {{ scope.row.status === "1" ? '启用' : '停用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="15%">
                <template #default="scope">
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">停用</el-button>
                    <el-button type="primary" size="small" style="margin-left: 6px"
                        @click="handleEdit(scope.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-bar">
            <el-pagination v-model:current-page="pagination.cur" v-model:page-size="pagination.size"
                :total="pagination.total" :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handlePageChange" />
        </div>

        <!-- 弹窗组件 -->
        <AddMealItemDialog ref="addDialogRef" @success="fetchData" />
        <EditMealItemDialog ref="editDialogRef" @success="fetchData" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { inject } from 'vue'
const axios = inject("axios")
import { ElMessage, ElMessageBox } from 'element-plus'
import AddMealItemDialog from '@/components/meal/mealItem/AddMealItemDialog.vue'
import EditMealItemDialog from '@/components/meal/mealItem/EditMealItemDialog.vue'

const addDialogRef = ref()
const editDialogRef = ref()
const openAddDialog = () => addDialogRef.value.open()

const searchForm = ref({ name: '' })
const tableData = ref([])

const pagination = ref({
    cur: 1,
    size: 10,
    total: 0
})

// 查询数据
const fetchData = async () => {
    try {
        const res = await axios.get('/mealitem/pageMealitem', {
            params: {
                cur: pagination.value.cur,
                number: pagination.value.size,
                name: searchForm.value.name
            }
        })
        if (res.data.status === 200) {
            tableData.value = res.data.data || []
            pagination.value.total = res.data.total
        } else {
            throw new Error(res.data.msg || '加载失败')
        }
    } catch (err) {
        ElMessage.error('查询失败：' + err.message)
    }
}

// 修改图片
const handleChangeImage = async (row, file) => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('mealItemId', row.mealitemId)

    try {
        const res = await axios.post('/file/uploadMealP', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.data.status === 200) {
            ElMessage.success('图片修改成功')
            fetchData()
        } else {
            ElMessage.error(res.data.msg || '图片修改失败')
        }
    } catch (err) {
        ElMessage.error('上传失败：' + err.message)
    }
    return false; // 禁止 el-upload 自动上传
}

const handleSizeChange = (size) => {
    pagination.value.size = size
    pagination.value.cur = 1
    fetchData()
}

const handlePageChange = (page) => {
    pagination.value.cur = page
    fetchData()
}

const handleDelete = (row) => {
    ElMessageBox.confirm(`确认要停用膳食项「${row.name}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await axios.post('/mealitem/deleteMealitem', null, {
                params: { mealitemId: row.mealitemId }
            })
            if (res.data.status === 200) {
                ElMessage.success('停用成功')
                fetchData()
            } else {
                throw new Error(res.data.msg || '停用失败')
            }
        } catch (err) {
            ElMessage.error('停用失败：' + err.message)
        }
    }).catch(() => { })
}

const handleEdit = (row) => {
    editDialogRef.value.open(row)
}

const resetSearch = () => {
    searchForm.value.name = ''
    pagination.value.cur = 1
    fetchData()
}

onMounted(fetchData)
</script>

<style scoped>
.page-root {
    padding: 0 3%;
    max-width: 1200px;
    margin: 0 auto;
    background-color: #fff;
}

.main-title {
    font-size: 27.2px;
    font-weight: bold;
    margin-top: 0;
}

.search-bar {
    margin-bottom: 20px;
}

.pagination-bar {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: 2%;
    margin-bottom: 2%;
}
</style>
